package leetCode.offer29;

public class Solution1 implements Solution{


    @Override
    public int[] spiralOrder(int[][] matrix) {
        if(matrix==null||matrix.length==0) return new int[0];
        if(matrix.length==1) return matrix[0];

        // 方向定义 1--向右 2--向下 3--向左 4--向上
        int direction = 1;
        int[] result = new int[matrix.length*matrix[0].length];
        int index = 1;
        int[][] position = new int[matrix.length][matrix[0].length];
        int row = 0,col = 0;
        result[0] = matrix[0][0];
        position[0][0] = -1;
        for(int i=1;i<matrix.length*matrix[0].length;i++) {

            if(direction==1) {
                if(col+1<matrix[0].length&&position[row][col+1]!=-1) {
                    result[index++] = matrix[row][col+1];
                    position[row][col+1] = -1;
                    col++;
                }else {
                    direction = 2;
                }
            }

            if(direction == 2) {
                if(row+1<matrix.length&&position[row+1][col]!=-1){
                    result[index++] = matrix[row+1][col];
                    position[row+1][col] = -1;
                    row++;
                }else{
                    direction = 3;
                }
            }

            if(direction == 3) {
                if(col-1>=0&&position[row][col-1]!=-1) {
                    result[index++] = matrix[row][col-1];
                    position[row][col-1] = -1;
                    col--;
                }else {
                    direction = 4;
                }
            }

            if(direction == 4){
                if(row-1>=0&&position[row-1][col]!=-1) {
                    result[index++] = matrix[row-1][col];
                    position[row-1][col] = -1;
                    row--;
                }else {
                    direction = 1;
                    i--;
                }
            }
        }
        return result;
    }



}
